#include<iostream>
#include<fstream>
#include"contacts.pb.h"

using namespace std;

void AddPeopleInfo(contacts::PeopleInfo* people)
{
    cout <<"--------------新增联系人---------------" << endl;
    cout << "请输入联系人姓名：";
    string name;
    getline(cin,name);
    people->set_name(name);

    cout << "请输入联系人年龄: " ;
    int age;
    cin >> age;
    people->set_age(age);
    cin.ignore(256,'\n');
    for(int i=0;;i++)
    {
        cout << "请输入联系人电话" << i+1<<"(只输入回车完成电话新增)";
        string number;
        getline(cin,number);
        if(number.empty())
        {
            break;
        }

        contacts::PeopleInfo_Phone* phone = people->add_phone();
        phone->set_number(number);


        cout << "请输入电话类型（1、移动电话  2.固定电话）";
        int type;
        cin >> type;
        cin.ignore(256,'\n');
        //设置联系人电话类型
        switch (type)
        {
        case 1:
            phone->set_type(contacts::PeopleInfo_Phone_PhoneType::PeopleInfo_Phone_PhoneType_MP);
            break;
        case 2:
            phone->set_type(contacts::PeopleInfo_Phone_PhoneType::PeopleInfo_Phone_PhoneType_TEL);
            break;
        default:
            cout << "选择有误" << endl;
            break;
        }

    }

    cout <<"--------------添加联系人成功-------------" << endl;
}


int main()
{
    contacts::Contacts contacts;
    //先读取本地已存在的联系人文件
    fstream input("constacts.bin",ios::in | ios::binary); 
 
    //文件不存在
    if(!input)
    {
        cout << "constacts.bin not find ,create new file ! " << endl;
    }
    else if(!contacts.ParseFromIstream(&input))
    {
        cerr << "parse error !" << endl;
        input.close();
        return -1;
    }
    //想通讯录中添加一个联系人
    AddPeopleInfo(contacts.add_contacts());

    //将通讯录写入本地文件中
    fstream output("constacts.bin",ios::out|ios::trunc|ios::binary);
    if(!contacts.SerializeToOstream(&output))
    {
        cerr << "write errpr !" << endl;
        input.close();
        output.close();
        return -1;
    }

    cout << "write success !" << endl;
    input.close();
    output.close();

    return 0;
}